package com.hopes.bizz.poll.hj212.listener;

import com.hopes.bizz.common.mq.constant.BizzActiveMqConstant;
import com.hopes.bizz.poll.activemq.consumer.ActiveMqQueueConsumer;
import com.hopes.bizz.poll.hj212.server.handler.DataHandlerChain;
import com.hopes.bizz.poll.hj212.server.handler.DataParseThread;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;

/**
 * @author daijie
 * @version 1.0
 * @date 2023/5/25 14:09
 * @Description:
 */
@Component
@Slf4j
public class HJ212MessageListener implements MessageListener, CommandLineRunner {
    @Autowired
    private ThreadPoolTaskExecutor taskExecutor;
    @Autowired
    private DataHandlerChain dataHandlerChain;
    @Autowired
    private ActiveMqQueueConsumer activeMqQueueConsumer;

    @Override
    public void onMessage(Message message) {
        String data = null;
        try {
            data = message.getBody(String.class);
        } catch (JMSException e) {
            log.error("消息消费失败,原因: {}", e.getMessage());
        }
        log.info("消息主体内容: {}",data);
        // 执行数据解析
        taskExecutor.execute(new DataParseThread(data, dataHandlerChain));
    }

    @Override
    public void run(String... args) throws Exception {
        try {
            activeMqQueueConsumer.addConsumer(BizzActiveMqConstant.KEY_QUEUE_HJ212, this);
        } catch (Exception e) {
            log.error("消费者创建失败,原因: {}", e.getMessage());
        }
    }
}
